﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace AIStudio.Wpf.DiagramDesigner
{
    public static class SelectionProps
    {
        #region EnabledForSelection

        public static readonly DependencyProperty EnabledForSelectionProperty =
            DependencyProperty.RegisterAttached("EnabledForSelection", typeof(bool), typeof(SelectionProps),
                new FrameworkPropertyMetadata((bool)false,
                    new PropertyChangedCallback(OnEnabledForSelectionChanged)));

        public static bool GetEnabledForSelection(DependencyObject d)
        {
            return (bool)d.GetValue(EnabledForSelectionProperty);
        }

        public static void SetEnabledForSelection(DependencyObject d, bool value)
        {
            d.SetValue(EnabledForSelectionProperty, value);
        }

        private static void OnEnabledForSelectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement fe = (FrameworkElement)d;
            if ((bool)e.NewValue)
            {
                fe.PreviewMouseDown += Fe_PreviewMouseDown;
            }
            else
            {
                fe.PreviewMouseDown -= Fe_PreviewMouseDown;
            }
        }

        #endregion

        static void Fe_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (((FrameworkElement)sender).DataContext is ISelectable selectable)
            {
                if (selectable.IsHitTestVisible)
                {
                    if ((Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != ModifierKeys.None)
                    {
                        if ((Keyboard.Modifiers & (ModifierKeys.Shift)) != ModifierKeys.None)
                        {
                            //selectable.IsSelected = !selectable.IsSelected;
                            selectable.AddToSelection(!selectable.IsSelected, false);
                        }

                        if ((Keyboard.Modifiers & (ModifierKeys.Control)) != ModifierKeys.None)
                        {
                            //selectable.IsSelected = !selectable.IsSelected;
                            selectable.AddToSelection(!selectable.IsSelected, false);
                        }
                    }
                    else if (!selectable.IsSelected)
                    {

                        selectable.AddToSelection(true, true);
                    }
                }
            }
        }
    }
}
